package com.wanxin.relam;

import com.wanxin.pojo.User;
import com.wanxin.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author common
 */
@Component
public class MyRelam extends AuthorizingRealm {
    @Autowired
    private UserService userService;


    /**
     * @return
     * @throws AuthenticationException
     *
     *  自定义登入认证， 配置生效后，当shiro的login方法被调用执行时，底层会自动的调用该方法完成登入认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的身份
        String username = token.getPrincipal().toString();
        //根据用用户的身份去数据库查询用户信息
        User user = userService.selectInfoUserService(username);
        if (user!=null) {
            AuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(),user.getUpassword(), ByteSource.Util.bytes("bjsxt"),token.getPrincipal().toString());
            return info;
        }
        return null;
    }

    /**
     * @return
     *  自定义授权方法
     * 该方法是由shiro自动触发，调用该方法获取当前认证成功的用户的权限信息
     *  然后shiro获取到当前方法的返回值，自动的进行权限校验，如果校验成功
     * 则正常执行对应的资源，校验失败则报错
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权开始");
        //获取当前用户的身份信息(登入名)
        String uname = (String) principalCollection.getPrimaryPrincipal();
        //查询当前用户具备的权限信息(从数据库查询)
        List<String> listPrower=userService.selectProwerUserService(uname);
        //查询当前用户的角色信息(从数据库查询)
        List<String> listRole= userService.selectRoleUserService(uname);

        //将当前用户具备的权限信息交给shiro
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(listPrower);
        info.addRoles(listRole);
        //info.addRole("emp"); 验证角色
        //返回
        return info;
    }
}
